use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::pages::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub slug: Option<String>,
    pub position: i32,
    pub show_breadcrumb: bool,
    pub active: bool,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Slug must not be empty."))]
    pub slug: Option<String>,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            slug: self.slug.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::pages::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a page by the provided id
    ///
    /// # Errors
    ///
    /// When could not find page or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let page = pages::Entity::find()
            .filter(model::query::condition().eq(pages::Column::Id, id).build())
            .one(db)
            .await?;
        page.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds a page by the provided slug
    ///
    /// # Errors
    ///
    /// When could not find page or DB query error
    pub async fn find_by_slug(db: &DatabaseConnection, slug: &str) -> ModelResult<Self> {
        let page = pages::Entity::find()
            .filter(
                model::query::condition()
                    .eq(pages::Column::Slug, slug)
                    .build(),
            )
            .one(db)
            .await?;
        page.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// Asynchronously creates a page and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the page into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        if let Some(slug) = &params.slug {
            if pages::Entity::find()
                .filter(
                    model::query::condition()
                        .eq(pages::Column::Slug, slug)
                        .build(),
                )
                .one(&txn)
                .await?
                .is_some()
            {
                return Err(ModelError::EntityAlreadyExists {});
            }
        }

        let page = pages::ActiveModel {
            slug: ActiveValue::set(params.slug.clone()),
            position: ActiveValue::set(params.position),
            show_breadcrumb: ActiveValue::set(if params.show_breadcrumb { 1 } else { 0 }),
            active: ActiveValue::set(if params.active { 1 } else { 0 }),
            viewed: ActiveValue::set(0),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(page)
    }
}

impl ActiveModel {
    /// Updates the page's active status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_active_status(
        mut self,
        db: &DatabaseConnection,
        active: bool,
    ) -> ModelResult<Model> {
        self.active = ActiveValue::set(if active { 1 } else { 0 });
        Ok(self.update(db).await?)
    }

    /// Updates the page's position
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_position(
        mut self,
        db: &DatabaseConnection,
        position: i32,
    ) -> ModelResult<Model> {
        self.position = ActiveValue::set(position);
        Ok(self.update(db).await?)
    }

    /// Updates the page's show breadcrumb status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_show_breadcrumb(
        mut self,
        db: &DatabaseConnection,
        show_breadcrumb: bool,
    ) -> ModelResult<Model> {
        self.show_breadcrumb = ActiveValue::set(if show_breadcrumb { 1 } else { 0 });
        Ok(self.update(db).await?)
    }

    /// Increments the page's view count
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn increment_view_count(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
        let current_views = self.viewed.unwrap();
        self.viewed = ActiveValue::set(current_views + 1);
        Ok(self.update(db).await?)
    }
}
